//
//  HomeViewController.m
//  Onskysell
//
//  Created by cg on 17/3/6.
//  Copyright © 2017年 cg. All rights reserved.
//

#import "HomeViewController.h"
#import "WebViewController.h"
#import "LJWebKitSupport.h"
#import "NetFailView.h"
#import "ShareHelp.h"
#import "topBarView.h"
#import "LYBaseWKWebView.h"

@interface HomeViewController ()<UIScrollViewDelegate,WKNavigationDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) NetFailView *netFailView;
@property (nonatomic, strong) topBarView *topBarView;

@property (nonatomic, strong) UIImageView *waitImageView;//因为要控制launchScreen时间(不采用didFinishLaunchingWithOptions阻塞线程来延长时间),又不想让开头出现短暂白屏,加入此处理

@property (nonatomic, strong) LYBaseWKWebView *wkHomeWeb;

@property (nonatomic, strong) NSTimer *requestTimer;


@property (nonatomic, copy) NSString *currentLoadUrl;
@property (nonatomic, copy) NSString *currentJs;
@property (nonatomic, copy) NSString *backUrl;

@property (nonatomic, assign) BOOL isNotFirstLoad;

//@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, strong) UIColor *statusBackColor;//前端设置的状态栏背景色

@property (nonatomic, copy) NSString *statusFontColor;//前端设置的状态栏前景色(black/white)

@property (nonatomic, assign) BOOL isGoBackForward;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];//因为初始加载launchScreen隐藏了,这里重新显示出来
    
    
    [self setupView];
    
    [self addConstraint];
    
    [self loadData];
    
//    [[LJWKWebCache shared] deleteCachesHome];
    [NotificationCenter addObserver:self selector:@selector(loadData) name:ReloadRootWebNoti object:nil];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.topView setBackgroundColor:self.statusBackColor];
    [self setStatusBarBackgroundColor:self.statusBackColor];
    if ([self.statusFontColor isEqualToString:@"black"]) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }
    else if ([self.statusFontColor isEqualToString:@"white"]) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    
//    if ([_currentLoadUrl rangeOfString:@"ossh52.cqlj023.com"  options:NSCaseInsensitiveSearch].location != NSNotFound) {
//         [self.wkHomeWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_currentLoadUrl]]];
//    }
    [NotificationCenter addObserver:self selector:@selector(jsEvent:) name:JSKNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(changeColor:) name:CHANGECOLORKNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(changeWordColor:) name:CHANGEWORDCOLORNoti object:nil];
    //现在截屏不需要分享了~!
//    [NotificationCenter addObserver:self selector:@selector(userDidTakeScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];

    [NotificationCenter addObserver:self selector:@selector(refreshNet:) name:RefreshNetNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(netFailBackHome:) name:NetFailBackHomeNoti object:nil];
    [NotificationCenter addObserver:self selector:@selector(topBarBackClick) name:TopBarBack object:nil];
    
    [NotificationCenter addObserver:self selector:@selector(applicationDidEnterForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [NotificationCenter addObserver:self selector:@selector(applicationDidEnterForeground) name:Foreground_Push_Get object:nil];
}

- (void)applicationDidEnterForeground
{
    NSDictionary *ext = [[NSUserDefaults standardUserDefaults] objectForKey:@"UMPushInfoDic"];
    if (ext) {
        [self handleWithPushNotiExt:ext];
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"UMPushInfoDic"];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [NotificationCenter removeObserver:self name:RefreshNetNotification object:nil];
    [NotificationCenter removeObserver:self name:JSKNotification object:nil];
    [NotificationCenter removeObserver:self name:CHANGECOLORKNotification object:nil];
    [NotificationCenter removeObserver:self name:CHANGEWORDCOLORNoti object:nil];
    //现在截频不需要分享了
//    [NotificationCenter removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    [NotificationCenter removeObserver:self name:NetFailBackHomeNoti object:nil];
    
    [NotificationCenter removeObserver:self name:TopBarBack object:nil];
    
    [NotificationCenter removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [NotificationCenter removeObserver:self name:Foreground_Push_Get object:nil];
}

- (void)dealloc
{
//    [self.wkHomeWeb removeObserver:self forKeyPath:@"URL"];
//    [self.wkHomeWeb removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)reloadWeb
{
    [self.wkHomeWeb reload];
}

- (void)setupView{
    
    self.topView = [[UIView alloc]init];
    [self.topView setBackgroundColor:StatusBarColor];
    [self.view addSubview:self.topView];
    
    self.wkHomeWeb = [[LYBaseWKWebView alloc] initWithFrame:CGRectZero configuration:[LJWebKitSupport sharedSupport].webViewConfiguration];
    //    self.wkHomeWeb.scrollView.backgroundColor = [UIColor whiteColor];
    self.wkHomeWeb.scrollView.scrollEnabled = NO;
    WS(wkSelf);
    self.wkHomeWeb.navigationDelegate = wkSelf;
    self.wkHomeWeb.scrollView.delegate = wkSelf;
    self.wkHomeWeb.scrollView.showsVerticalScrollIndicator = NO;
    self.wkHomeWeb.scrollView.showsHorizontalScrollIndicator = NO;
//    [self.wkHomeWeb addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];//防内存过大白屏处理

    [self.view addSubview:self.wkHomeWeb];
     
    [self.navigationController setNavigationBarHidden:YES];
    
    [[CGLodingView shareInstance] startAnimation];//第一次进来在启动页后面loading
    
    self.waitImageView = [[UIImageView alloc] init];
    if ([LJUtility isIphoneX]) self.waitImageView.image = [UIImage imageNamed:@"iphonexPreLaunch"];
    else self.waitImageView.image = [UIImage imageNamed:@"preLaunchImg"];
    
    KWindow.windowLevel = UIWindowLevelAlert;//包括statusbar
    
    [KWindow addSubview:self.waitImageView];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:WaitingTimerOut target:self selector:@selector(dismissWaitView:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
}

- (UIColor *)statusBackColor
{
    if (!_statusBackColor) {
        _statusBackColor = StatusBarColor;//默认
    }
    return _statusBackColor;
}

- (NSString *)statusFontColor
{
    if (!_statusFontColor) {
        _statusFontColor = @"black";
    }
    return _statusFontColor;
}

- (void)addConstraint{
    
    [self.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(@(0));
        make.height.equalTo(@(StatusBarHeight));
    }];
    
    [self.wkHomeWeb mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(@(StatusBarHeight));
        make.bottom.equalTo(@(0));
    }];
    
    [self.waitImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(KWindow);
    }];
}



- (void)loadData{

    NSString *theUrl = self.theLoadUrl?:BaseWebUrl;
    NSDictionary *ext = [[NSUserDefaults standardUserDefaults] objectForKey:@"UMPushInfoDic"];
    if (ext) {
        NSNumber *type = [ext objectForKey:@"type"];
        NSString *url = [ext objectForKey:@"url"];
        if (type) {
            if ([type isKindOfClass:NSNumber.class]) {
                if (type.integerValue == 1) {//跳转链接
                    if (url) {
                        if ([LJUtility theString:url containSting:BaseHost]) {
                            theUrl = url;
                        }
                    }
                }
            }
        }
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"UMPushInfoDic"];
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:theUrl]];
    [self.wkHomeWeb loadRequest:request];
}

- (void)handleWithPushNotiExt:(NSDictionary *)ext
{
    if (ext) {
        NSNumber *type = [ext objectForKey:@"type"];
        NSString *url = [ext objectForKey:@"url"];
        if (type) {
            if ([type isKindOfClass:NSNumber.class]) {
                if (type.integerValue == 1) {//跳转链接
                    if (url) {
                        if ([LJUtility theString:url containSting:BaseHost]) {
                            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
                            [self.wkHomeWeb loadRequest:request];
                        }
                        else {
                            
                        }
                    }
                }
            }
        }
    }
}

#pragma mark ======= observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.wkHomeWeb && [keyPath isEqualToString:@"estimatedProgress"]) {
//        [self.progressView setAlpha:1.0f];//0.10000000000000001起
//        
//        BOOL animated = self.wkHomeWeb.estimatedProgress > self.progressView.progress;
//        [self.progressView setProgress:self.wkHomeWeb.estimatedProgress animated:animated];
//        
//        if(self.wkHomeWeb.estimatedProgress >= 1.0f) {
//            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
//                [self.progressView setAlpha:0.0f];
//                
//            } completion:^(BOOL finished) {
//                [self.progressView setProgress:0.0f animated:NO];
//            }];
//        }
    }
    else if (object == self.wkHomeWeb && [keyPath isEqualToString:@"URL"])
    {
        NSURL *newUrl = [change objectForKey:NSKeyValueChangeNewKey];
        NSURL *oldUrl = [change objectForKey:NSKeyValueChangeOldKey];
        if (IsNull(newUrl) && !IsNull(oldUrl)) {
            //            processDidTerminated = YES;
            [self.wkHomeWeb reload];
        };
    }
}

#pragma mark ======= UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if ([_currentLoadUrl isEqualToString:BaseURL]) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
    else if ([LJUtility theString:_currentLoadUrl containSting:[NSString stringWithFormat:@"%@%@",BaseHost,@"/Home"]]) {
        if (scrollView.contentOffset.y<=0) {
            scrollView.contentOffset = CGPointMake(0, 0);
        }
    }
}

#pragma mark ======= WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSString *url = webView.URL.absoluteString;
    
    NSLog(@"网页开始加载");
    [OKWebViewURLFilter shared].startTimeMsecs = [[NSDate date] timeIntervalSince1970]*1000;
    if (self.requestTimer) {
        [self stopTimer];
    }
    
    self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:RequestTimeout target:self selector:@selector(requestTimeOut:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:self.requestTimer forMode:NSRunLoopCommonModes];
    if (self.isNotFirstLoad) {
        if ([[OKWebViewURLFilter shared] filterLoadingUrl:url]) {
            [[CGLodingView shareInstance] startAnimation];
        }
    }
    else self.isNotFirstLoad = YES;
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"网页加载完成");
    NSString *url = webView.URL.absoluteString;
    [[CGLodingView shareInstance] stopAnimation];
    if (DebugMode) [[OKWebViewURLFilter shared] showLoadTimeDif];
    [self stopTimer];
    
    if (!webView.isLoading) {
            if ([self.backUrl isEqualToString:BaseURL] && self.isGoBackForward) {
                self.isGoBackForward = NO;
                self.backUrl = nil;
                [self loadJsWithJs:@"updateServicenew('xxxxtest')"];
            }
            //首页上传deviceToken处理
            else if ([LJUtility theString:_currentJs containSting:@"updateService("]) {
                [self loadJsWithJs:_currentJs];
            }
    }
    
    if (url) {
        if ([url containsString:BaseWebUrl] || [url containsString:@"http://ios_jsapi"]) {
            [self dismissTobBarView];
        }
        else {//外域
            [self showTobBarView];
        }
    }
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [self handleNetFailWeb];
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *url = [navigationAction.request.URL absoluteString];
    
    //UIWebView打开一个页面之后，点击里面的内容就直接能跳转。而WKWebView一开始点里面的东西没反应，只要加了这个方法就好了
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    
    if (navigationAction.navigationType == WKNavigationTypeBackForward) {//监测web返回
        self.backUrl = url;
        self.isGoBackForward = YES;
    }
        
    if ([LJUtility theString:url containSting:[NSString stringWithFormat:@"%@/Bid/Detail",BaseHost]] || [LJUtility theString:url containSting:[NSString stringWithFormat:@"%@/Bid/MyBidDetail",BaseHost]]) {//新开web
        
        WebViewController *web = [[WebViewController alloc] init];
        web.lastWeb = self.wkHomeWeb;
        web.homeWeb = self.wkHomeWeb;
        web.UrlString = url;
        [self.navigationController pushViewController:web animated:YES];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else {
        if ([[OKWebViewURLFilter shared] filter:navigationAction.request WebView:webView viewController:self]) {
            self.currentLoadUrl = url;
            [[NSNotificationCenter defaultCenter] postNotificationName:CHANGECOLORKNotification object:@"#ffffff"];
            [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEWORDCOLORNoti object:@"#000000"];
            decisionHandler(WKNavigationActionPolicyAllow);
        }
        else {
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
}



#pragma mark - =========== Other

- (void)jsEvent:(NSNotification *)notif{
    NSString *notiString = [notif object];
    
    self.currentJs = notiString;
    if (![LJUtility theString:_currentJs containSting:@"updateService("]) {//非首页上传deviceToken
        [self loadJsWithJs:notiString];
    }
}

- (void)loadJsWithJs:(NSString *)js
{
    //ios11要求evaluateJavaScript主线程
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.wkHomeWeb evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            [[CGLodingView shareInstance] stopAnimation];
            if (error) {
                NSLog(@"wkHomeWeb evaluateJavaScript error = %@\n", error);
            }
            _currentJs = nil;
        }];
    });
}

//状态栏背景色
- (void)changeColor:(NSNotification *)notif{
    NSString *notiString = [notif object];
    self.statusBackColor = [UIColor colorWithHexString:notiString];
    [self.topView setBackgroundColor:self.statusBackColor];
    [self setStatusBarBackgroundColor:self.statusBackColor];//这里若不设置会出现弹出键盘时等状态栏跳色的问题
}

//状态栏前景色
- (void)changeWordColor:(NSNotification *)notif{
    NSString *notiString = [notif object];
    self.statusFontColor = notiString;
    if ([notiString isEqualToString:@"black"] || [notiString isEqualToString:@"#000000"]) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }
    else if ([notiString isEqualToString:@"white"] || [notiString isEqualToString:@"#ffffff"]) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
}

//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)showTobBarView
{
    if (self.topBarView) {
        return;
    }
    
    self.topBarView = [[NSBundle mainBundle] loadNibNamed:@"topBarView" owner:nil options:nil].firstObject;
    self.topBarView.frame = CGRectMake(0, StatusBarHeight, CGRectGetWidth(self.view.frame), 44);
    [self.view addSubview:self.topBarView];
    [self.view bringSubviewToFront:self.topBarView];
    
    [self.wkHomeWeb mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(@(StatusBarHeight+44));
        make.bottom.equalTo(@(0));
    }];
}

- (void)dismissTobBarView
{
    if (self.topBarView) {
        [self.topBarView removeFromSuperview];
        self.topBarView = nil;
        [self.wkHomeWeb mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(0));
            make.right.equalTo(@(0));
            make.top.equalTo(@(StatusBarHeight));
            make.bottom.equalTo(@(0));
        }];
    }
}

- (void)requestTimeOut:(NSTimer *)timer{
//    if (self.webLoadFinished == NO) {
        [self handleNetFailWeb];
//    }
    
}

- (void)handleNetFailWeb
{
    [[CGLodingView shareInstance] stopAnimation];
    [self stopTimer];
    
    if (self.netFailView) {
        return;
    }
    
    [self toErrorWeb];
}

- (void)stopTimer{
    [self.requestTimer invalidate];
    self.requestTimer = nil;
}

- (void)toErrorWeb{
    self.netFailView = [[NSBundle mainBundle] loadNibNamed:@"NetFailView" owner:nil options:nil].firstObject;
    self.netFailView.frame = CGRectMake(0, StatusBarHeight, CGRectGetWidth(self.wkHomeWeb.frame),CGRectGetHeight(self.wkHomeWeb.frame));
    if (![CGNetManage isReachable]) {
        [self.netFailView setNoNetNotice];
    }
    [self.view addSubview:self.netFailView];
}

- (void)refreshNet:(NSNotification *)notification
{

    if (![CGNetManage isReachable]) {
        [self.netFailView setNoNetNotice];
        [self stopTimer];
        return;
    }
    
//    //清空web
//    [self.wkHomeWeb evaluateJavaScript:@"document.body.innerHTML='';" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        if (error) {
//            NSLog(@"wkHomeWeb evaluateJavaScript error = %@\n", error);
//        }
//    }];
    
    [self.netFailView removeFromSuperview];
    self.netFailView = nil;
    [self.wkHomeWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.currentLoadUrl]]];
}

- (void)netFailBackHome:(NSNotification *)notification
{
    if (![CGNetManage isReachable]) {//无网
        [self.netFailView setNoNetNotice];
        [self stopTimer];
        
    }
    else {//有网重新加载首页
        [self.netFailView removeFromSuperview];
        self.netFailView = nil;

        [self.wkHomeWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:BaseWebUrl]]];
    }
    
}

- (void)topBarBackClick
{
    if ([self.wkHomeWeb canGoBack]) {
        [self loadJsWithJs:@"javascript:history.back(-1)"];
    }
}

- (void)dismissWaitView:(NSTimer *)timer
{
    KWindow.windowLevel = UIWindowLevelNormal;
    [self.waitImageView removeFromSuperview];
    self.waitImageView = nil;
    [timer invalidate];
    timer = nil;
}


- (void)userDidTakeScreenshot:(NSNotification *)notification
{
    NSLog(@"检测到截屏");
    UIImage *img = [LJUtility getScreenshotImg];
    
    [CGNetManage httpPostImg:img compress:0.5 success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSString *imgPath;
        if ([[[dic objectForKey:@"state"] objectForKey:@"code"] intValue] == 200) {
            NSArray *pathArr = [dic objectForKey:@"data"];
            if (pathArr.count>0) {
                if (imgPath == nil) {
                    imgPath = pathArr.firstObject;
                    [[NSUserDefaults standardUserDefaults] setObject:imgPath forKey:@"screenshotUrl"];
                    [[ShareHelp shared] shareWithTitle:ScreenShotTitle content:nil image:img url:BaseWebUrl currentController:self fromType:FromScreenshot];
                }
            }
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"截屏图片上传失败~");
    }];
    
//    [[ShareHelp shared] shareWithTitle:ScreenShotTitle content:nil image:img url:BaseWebUrl currentController:self fromType:FromScreenshot];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
